var DEBUG = false;
var BASICURL = 'https://www.tsdy.club/tomato-schedule/api/'
import store from '../store';
import { paramObj } from './param';
// import mockArr from '../../mock/index';
import { getToken } from './token';


var request = Function;
var tokenRequest = Function;

if (DEBUG) {
  request = function (config) {
    return new Promise(function (resolve, reject) {
      var success = false;
      for (let item of mockArr) {
          if (item.url == config.url && item.method == config.method) {
          try {
            resolve(item.response(config));
          } catch (err) {
            reject(err);
            return ;
          }
          success = true;
          break;
        }

      }
      if (!success) {
        resolve(new Error('no match url or method'))
      }
    })

  }
} else {
  request = function (config) {
    let { url, method, data, param, header } = config;
    if (param) {
      url = paramObj(url, param);
    }
    return new Promise(function (resolve, reject) {
        let token = '';
        token = getToken();
      wx.request({
        url: BASICURL + url,
        method,
        data,
        header: {
            ...header
        },
        success(res) {
          resolve(res)
        },
        fail(res) {
          reject(res)
        }
      })
    })
  }

  tokenRequest = function (config) {
    let { url, method, data, param, header } = config;
    if (param) {
      url = paramObj(url, param);
    }
    return new Promise(function (resolve, reject) {
        let token = '';
        token = getToken();
      wx.request({
        url: BASICURL + url,
        method,
        data,
        header: {
            token,
            ...header
        },
        success(res) {
          if (res.data.code > 10000 && res.data.code <= 10010) {
            store.dispatch("login")
            .then(() => {resolve(res)})
          } else {
            resolve(res)
          }
          
        },
        fail(res) {
          reject(res)
        }
      })
    })
  }
  
}

export { request, tokenRequest };
